import React from 'react'
import { createBehavior } from '@bill_law6/designable-core'
import { DnFC } from '@bill_law6/designable-react'
import { useField, observer, Field as FormilyField } from '@formily/react'
import { Label } from '../../ui/label'
import { cn } from '../../lib/utils'
import { AllLocales } from '../../locales'

export interface FieldProps {
  title?: string
  description?: string
  required?: boolean
  className?: string
  children?: React.ReactNode
}

export const Field: DnFC<FieldProps> = observer((props) => {
  const field = useField()
  
  if (!field) return <>{props.children}</>
  
  const { title, description, required, className, children } = props
  
  return (
    <div className={cn('space-y-2', className)}>
      {title && (
        <Label htmlFor={field.address.toString()}>
          {title}
          {required && <span className="text-destructive ml-1">*</span>}
        </Label>
      )}
      {children}
      {description && (
        <p className="text-sm text-muted-foreground">{description}</p>
      )}
      {field.errors.length > 0 && (
        <div className="text-sm text-destructive">
          {field.errors.join(', ')}
        </div>
      )}
    </div>
  )
})

Field.Behavior = createBehavior({
  name: 'Field',
  selector: (node) => node.componentName === 'Field',
  designerProps: {
    droppable: true,
    propsSchema: {
      type: 'object',
      properties: {
        title: {
          type: 'string',
          'x-decorator': 'FormItem',
          'x-component': 'Input',
        },
        description: {
          type: 'string',
          'x-decorator': 'FormItem',
          'x-component': 'Input.TextArea',
        },
        required: {
          type: 'boolean',
          'x-decorator': 'FormItem',
          'x-component': 'Switch',
        },
      },
    },
  },
  designerLocales: AllLocales.Field,
})